import {createRouter,createWebHashHistory} from 'vue-router';
import Login from '../views/Login.vue';
import MainBox from '../views/MainBox.vue';
import Forget from '../views/Forget.vue';

import RouteConfig from './config';
import NotFound from '../views/notfound/NotFound.vue'

import {useRouterStore} from '../store/useRouterStore'
import {useUserStore} from '../store/useUserStore'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const routes =[
    {
        path:"/login",
        name:"login",
        component:Login
    },
    {
        path:"/forget",
        name:"forget",
        component:Forget
    },
    {
        path:"/mainbox",
        name:"mainbox",
        component:MainBox
    }
]

const router = createRouter({
    history:createWebHashHistory(),
    routes
})

// 路由拦截
router.beforeEach((to,from,next)=>{
    //显示进度条
    NProgress.start();

    const{isGetterRouter} = useRouterStore()
    const{user} = useUserStore()
    if(to.name==="login"||to.name==="forget"){
        next();
    }else{
        if(!user.role){
            // 跳转登录
            next({
                path:"/login"
            })
        }else{
            if(!isGetterRouter){
                router.removeRoute("mainbox")
                ConfigRouter();
                next({
                    path:to.fullPath
                });
            }else{
                next()
            }
            
        }
    }
})

router.afterEach(()=>{
    //关闭进度条
    NProgress.done();
})


const ConfigRouter = ()=>{
    // 创建mainbox
    router.addRoute({
        path:"/mainbox",
        name:"mainbox",
        component:MainBox
    })

    let {changeRouter} = useRouterStore();

    RouteConfig.forEach(item=>{
        checkPermission(item.path) && router.addRoute("mainbox",item)
    })

    // 重定向
    router.addRoute("mainbox",{
        path:"/",
        redirect:"/index"
    })

    // 404
    router.addRoute("mainbox",{
        path:"/:pathMatch(.*)*",
        name:"not found",
        component:NotFound
    })

    changeRouter(true);
}

const checkPermission = (path)=>{
    const {user} = useUserStore()
    return user.role.rights.includes(path);
}

export default router;